import random
import json
from faker import Faker

fake = Faker('zh_CN')

# 商品类别
categories = ["电子产品", "服装鞋帽", "家居用品", "美妆个护", "母婴用品", "食品饮料", "图书音像", "运动户外"]


# 生成商品数据
def generate_products(num_products=1000):
    products = []
    for i in range(num_products):
        product = {
            "id": i + 1,
            "name": fake.text(max_nb_chars=20).replace('\n', ''),
            "category": random.choice(categories),
            "price": round(random.uniform(10, 10000), 2),
            "description": fake.text(max_nb_chars=200),
            "brand": fake.company(),
            "rating": round(random.uniform(1, 5), 1),
            "sales": random.randint(0, 10000),
            "images": [f"https://picsum.photos/seed/prod{i}/200/200"]
        }
        products.append(product)
    return products


# 生成用户数据
def generate_users(num_users=500):
    users = []
    for i in range(num_users):
        user = {
            "id": i + 1,
            "username": fake.user_name(),
            "email": fake.email(),
            "age": random.randint(18, 70),
            "gender": random.choice(["男", "女"]),
            "location": fake.province(),
            "preferences": random.sample(categories, random.randint(1, 4))
        }
        users.append(user)
    return users


# 生成用户行为数据（浏览、收藏、购买）
def generate_user_actions(users, products, num_actions=10000):
    actions = []
    action_types = ["view", "collect", "buy"]
    for _ in range(num_actions):
        user = random.choice(users)
        product = random.choice(products)

        # 用户更倾向于浏览自己偏好类别的商品
        if product["category"] in user["preferences"]:
            if random.random() < 0.8:
                action_type = random.choice(action_types)
            else:
                action_type = "view"
        else:
            if random.random() < 0.3:
                action_type = "view"
            else:
                continue

        action = {
            "user_id": user["id"],
            "product_id": product["id"],
            "action_type": action_type,
            "timestamp": fake.date_time_this_year().isoformat()
        }
        actions.append(action)
    return actions


# 保存数据到JSON文件
def save_to_json(data, filename):
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)


if __name__ == "__main__":
    products = generate_products()
    users = generate_users()
    actions = generate_user_actions(users, products)

    save_to_json(products, "data/products.json")
    save_to_json(users, "data/users.json")
    save_to_json(actions, "data/actions.json")

    print("数据生成完成！")